import numpy as np
from matplotlib import pyplot as plt
import pandas as pd

def TransMat(mat):
    mat = mat.T
    return mat

def fun1():
    mat1 = pd.read_csv("./数据.csv")
    mat1 = np.array(mat1)
    # print(TransMat(mat1))
    df1 = pd.DataFrame(data=TransMat(mat1), index=['dataA', 'dataB'])
    mat1 = mat1.reshape(10, 10)
    print(mat1)
    df2 = pd.DataFrame(data=mat1)
    df1.to_csv("./New_T_Data.csv")
    df2.to_csv("./10_10mat.csv")

def fun_fcsjsjy():
    """
    组限表数据划分
    :return:
    """
    mat1 = pd.read_csv("./数据.csv")
    mat1 = np.array(mat1)
    mat1 = mat1.reshape(100)
    mat1 = np.sort(mat1)
    print(mat1)
    step = (mat1.max()-mat1.min())/8
    G1 = []
    G2 = []
    G3 = []
    G4 = []
    G5 = []
    G6 = []
    G7 = []
    G8 = []
    for i in range(mat1.shape[0]):
        if mat1[i] <= mat1.min() + step:
            G1.append(mat1[i])
        elif mat1[i] <= mat1.min() + 2 * step and mat1[i] > mat1.min() + step:
            G2.append(mat1[i])
        elif mat1[i] <= mat1.min() + 3 * step and mat1[i] > mat1.min() + 2 * step:
            G3.append(mat1[i])
        elif mat1[i] <= mat1.min() + 4 * step and mat1[i] > mat1.min() + 3 * step:
            G4.append(mat1[i])
        elif mat1[i] <= mat1.min() + 5 * step and mat1[i] > mat1.min() + 4 * step:
            G5.append(mat1[i])
        elif mat1[i] <= mat1.min() + 6 * step and mat1[i] > mat1.min() + 5 * step:
            G6.append(mat1[i])
        elif mat1[i] <= mat1.min() + 7 * step and mat1[i] > mat1.min() + 6 * step:
            G7.append(mat1[i])
        else:
            G8.append(mat1[i])
    G = [G1, G2, G3, G4, G5, G6, G7, G8]
    for i in range(8):
            print("{}-{}:{}".format(mat1.min() + step * i, mat1.min() + step * (i+1), len(G[i])))
    return G

def TJ():
    """
    统计数据的操作计算
    :return:
    """
    mat1 = pd.read_csv("./数据.csv")
    mat1 = np.array(mat1)
    mat_rem =mat1
    mat1 = mat1.reshape(100)
    mat1 = np.sort(mat1)
    u = np.sum(mat1)/mat1.shape[0]
    print("u:", u)
    segma = np.sum((mat1 - u) ** 2)/mat1.shape[0]
    print("segma:", segma)
    step = (mat1.max() - mat1.min()) / 8
    Xi = []
    for i in range(9):
        Xi.append(mat1.min() + step * i)
    print(Xi)
    Xi = np.array(Xi)
    Xi = (Xi-u)/segma**(0.5)
    print(Xi)
    fai = np.array([0.0119, 0.0495, 0.1515, 0.3372, 0.5793, 0.791, 0.9236, 0.9793, 0.996])
    Pi=[]
    for i in range(fai.shape[0]-1):
        Pi.append(fai[i+1] - fai[i])
    print("Pi:", Pi)
    Pi = np.array(Pi)
    minpi=[]
    Group = fun_fcsjsjy()
    for i in range(6):
        minpi.append(len(Group[i])-100*Pi[i])
    minpi.append(1.76)
    print("mi-npi:", minpi)
    kafang=[]
    for i in range(6):
        kafang.append((minpi[i])**2/(100*Pi[i]))
        print("(mi-npi)2/npi:", (minpi[i])**2/(100*Pi[i]))
    kafang.append(1.850)
    kafang = np.array(kafang)
    kafang = kafang.sum()
    print("kafang:", kafang)
    mat_p1 = mat_rem[:, 0]
    mat_p2 = mat_rem[:, 1]
    segma1 = np.sum((mat_p1 - 15.02) ** 2)/mat_p1.shape[0]
    segma2 = np.sum((mat_p2 - 15.02) ** 2) / mat_p2.shape[0]
    segma1 = np.sum(((mat_p1 - 15.02)/segma1**(0.5)) ** 2)
    segma2 = np.sum(((mat_p2 - 15.02) / segma2 ** (0.5)) ** 2)
    print("segma_p1:", segma1)
    print("segma_p1:", segma2)
    n_u = np.sum((mat_p1 - 15.02) ** 2)
    print("n_u:", n_u)

def segma_plt():
    mat1 = pd.read_csv("./数据.csv")
    mat1 = np.array(mat1)
    mat1 = mat1.reshape(100)
    plt.figure()
    nums, bins, patches = plt.hist(mat1, bins=8, color='c', edgecolor='w')
    plt.xticks(bins, bins)
    print(nums)
    print(bins)
    print(patches)
    for num, bin in zip(nums, bins):
        plt.annotate(num, xy=(bin, num), xytext=(bin + 0.00175, num + 0.5))
    plt.rcParams["font.sans-serif"] = ["SimHei"]
    plt.xlabel('组限', {'size': 16})
    plt.ylabel('频数', {'size': 16})
    plt.title('数据分布(By 3122301230)', {'size': 16})
    plt.show()

def For_S45():
    """
    45钢的正交分析
    :return:
    """
    mat_s = pd.read_csv("正交表.csv", names=[0, 1, 2, 3, 4, 5, 6])#添加names避免把数据作为表头
    mat_s = np.array(mat_s)
    a, b = mat_s.shape
    Tj1 = []
    Tj2 = []
    Tj3 = []
    Tj4 = []
    Tj5 = []
    for i in range(b-1):
        T1 = []
        T2 = []
        T3 = []
        T4 = []
        T5 = []
        for j in range(a):
            if mat_s[j][i] == 1:
                T1.append(mat_s[j][6])
            elif mat_s[j][i] == 2:
                T2.append(mat_s[j][6])
            elif mat_s[j][i] == 3:
                T3.append(mat_s[j][6])
            elif mat_s[j][i] == 4:
                T4.append(mat_s[j][6])
            elif mat_s[j][i] == 5:
                T5.append(mat_s[j][6])
        Tj1.append(np.array(T1).sum())
        Tj2.append(np.array(T2).sum())
        Tj3.append(np.array(T3).sum())
        Tj4.append(np.array(T4).sum())
        Tj5.append(np.array(T5).sum())
    T = [Tj1, Tj2, Tj3, Tj4, Tj5]
    T = np.array(T)
    R = np.row_stack((T, T.max(axis=0)-T.min(axis=0)))
    print("R:", R)
    R = pd.DataFrame(data=R)
    R.to_csv("正交表_R.csv")
    print("yi的和：", mat_s.sum(axis=0)[-1])
    print("n_segema_yi:", np.sum(mat_s[:, -1]**2)-1/25*(np.sum(mat_s[:, -1]))**2)
    print("Tsum", T.sum(axis=0))
    Q = 1/5*(np.sum(T**2, axis=0)) - 1/25*(np.sum(T, axis=0))**2
    print("Q:", Q[0:4])
    print("e:", ((mat_s[:, -1] - 0.510364)**2).sum() - Q[0:4].sum())
    print(Q/4, (((mat_s[:, -1] - 0.510364)**2).sum() - Q[0:4].sum())/8)
    print(Q/((((mat_s[:, -1] - 0.510364)**2).sum() - Q[0:4].sum())/8))

def hgfx():
    """
    45钢的回归分析
    :return:
    """
    mat_s = pd.read_csv("45钢数据.csv")
    mat_s = np.array(mat_s)
    a, b = mat_s.shape
    # print(mat_s)
    # print(a, b)
    ONE = np.ones([25, 1])
    X = mat_s[0:25, 1:-1]
    X = np.column_stack((ONE, X))
    Y = mat_s[0:25, -1]
    pd.DataFrame(data=X).to_csv("x.csv")
    pd.DataFrame(data=Y).to_csv("y.csv")
    # print(X)
    # print(Y)
    B = np.matmul(np.matmul(np.linalg.inv(np.matmul(X.T, X)), X.T), Y)
    B_rember = B
    # print("B:", B)
    x = mat_s[25:30, 1:-1]
    ONE = np.ones([5, 1])
    x = np.column_stack((ONE, x))
    print(x)
    B = np.column_stack((B.T, B.T, B.T, B.T, B.T))
    print(B)
    print("预测值：", np.matmul(x, B)[:, 0])
    print("真实值：", mat_s[25:30, -1])
    print("相对误差:", (np.matmul(x, B)[:, 0]-mat_s[25:30, -1])/mat_s[25:30, -1])
    y_u = mat_s[0:25, -1].sum()/25
    print("y_u:", y_u)
    B_B = B
    for i in range(4):
        B_B = np.column_stack((B_B, B))
    # print(B_B.shape)
    # print(X.shape)
    y_hat = np.matmul(X, B_B)
    print(y_hat[:, 0])
    y_hat = y_hat[:, 0]
    Qr = ((y_hat - y_u)**2).sum()
    print("Qr:", Qr)
    Qe = ((mat_s[0:25, -1] - y_hat)**2).sum()
    print("Qe:", Qe)
    Qt = ((mat_s[0:25, -1] - y_u)**2).sum()
    print("Qt:", Qt)
    print("Qr/k:", Qr/4)
    print("Qe/n-k-1:", Qe/20)
    print("F:", Qr/4/(Qe/20))
    C = np.linalg.inv(np.matmul(X.T, X))
    C_C = []
    for i in  range(C.shape[0]):
        for j in range(C.shape[1]):
            if i == j:
                C_C.append(C[i][j])
    C_C = np.array(C_C)
    print("C_C", C_C)
    t = B_rember/C_C**(0.5)/(Qe/20)**(0.5)
    print("t:", t)
    NB = B_rember[1:4]
    

if __name__ == '__main__':
    # fun1()
    # fun_fcsjsjy()
    # TJ()
    # segma_plt()
    # For_S45()
    hgfx()
